package com.boguan.device.weiyu;


import com.alibaba.fastjson.JSONObject;
import com.boguan.common.core.domain.AjaxResult;
import com.boguan.common.core.redis.RedisCache;
import com.boguan.common.utils.StringUtils;
import com.boguan.common.utils.http.HttpUtils;
import com.boguan.device.domain.Device;
import com.boguan.device.mapper.DeviceMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * 微羽设备对接
 *
 * @author chen
 * @date 2022-01-12
 */
@Component
public class WeiYuDeviceUtils {

    @Autowired
    public RedisCache redisCache;


    /**
     * 获取认证token
     *
     * @param weiyu_user
     */
    public String getToken(String weiyu_user) {
        String[] weiyu = weiyu_user.split("_");
        String username = weiyu[0];
        String pwd = weiyu[1];
        String accessToken = redisCache.getCacheObject("weiyu_Access_token");
        if (StringUtils.isNull(accessToken)) {
            String url = "http://47.110.53.42:9999/v3/Authorizations";
            Map<String, Object> map = new HashMap<>();
            map.put("uname", username);
            map.put("pwd", pwd);
            String result = HttpUtils.sendPostJSON(url, JSONObject.toJSONString(map), null);
            JSONObject jsonObject = JSONObject.parseObject(result);
            if ("200".equals(jsonObject.getString("code"))) {
                JSONObject data = jsonObject.getJSONObject("data");
                Integer expires_in = data.getInteger("expires_in");
                accessToken = data.getString("access_token");
                if (expires_in == null) {
                    expires_in = 24 * 60 * 60;
                }
                redisCache.setCacheObject("weiyu_Access_token", accessToken, expires_in, TimeUnit.SECONDS);
            }
        }
        return accessToken;
    }
}
